/*
 * Copyright (C) 2004, Velocityme Partnership
 * UserActions.java
 *
 * Created on 25 September 2004, 04:20
 */

package com.velocityme.www.interfaces.nodeactions;

import com.velocityme.entity.User;
import com.velocityme.session.KeyLocal;
import com.velocityme.session.NodeLocal;
import com.velocityme.session.UserLocal;
import com.velocityme.utility.DuplicateUserException;
import com.velocityme.utility.PasswordIncorrectException;
import com.velocityme.utility.PermissionDeniedException;
import com.velocityme.www.actionforms.ChangePasswordActionForm;
import com.velocityme.www.actionforms.nodeactionforms.UserActionForm;
import com.velocityme.www.interfaces.ShowNodeAction;
import com.velocityme.www.utility.NodeUtil;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJBException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 *
 * @author  Robert
 */
public class UserActions extends NodeActions {
    
    /** Creates a new instance of UserActions */
    public UserActions() {
    }
    
    @Override
    public ActionForward show(ActionMapping mapping, 
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        User user = lookupUserBean().findUser(key, nodeId);
        session.setAttribute("user", user);
        session.setAttribute("groups", lookupUserBean().getGroups(key, user));
        return mapping.findForward("ACTION_DISPLAY");
    }
    
    @Override
    public ActionForward showCreate(ActionMapping mapping, 
                                    ActionForm form,
                                    HttpServletRequest request,
                                    HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        User user = new User();
        user.setParentNode(lookupNodeBean().findNode(key, nodeId));
        session.setAttribute("user", user);
        session.setAttribute("userAF", new UserActionForm());
        session.setAttribute("personPairs", NodeUtil.getAllPersonPairs(key));
        return mapping.findForward("ACTION_EDIT");
    }
    
    @Override
    public ActionForward showEdit(ActionMapping mapping, 
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        User user = lookupUserBean().findUser(key, nodeId);
        session.setAttribute("user", user);
        UserActionForm userAF = new UserActionForm();
        userAF.setPersonId(user.getPerson().getId());
        session.setAttribute("userAF", userAF);
        session.setAttribute("personPairs", NodeUtil.getAllPersonPairs(key));
        return mapping.findForward("ACTION_EDIT");
    }
    
    @Override
    public ActionForward edit(ActionMapping mapping, 
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        Long nodeId;
        UserActionForm userValueAF = (UserActionForm)form;
        if (request.getParameter("btnSubmit").equals("OK")) {
            User user = (User)session.getAttribute("user");
            ((UserActionForm)form).extractUser(key, user);
            if (user.getId() != null) {
                lookupUserBean().editUser(key, user);
            }
            else {
                ActionErrors errors = new ActionErrors();
                String password = userValueAF.getPassword();
                try {
                    user = lookupUserBean().createUser(key, user, password);
                }
                catch(EJBException e) {
                    if (e.getCause() instanceof DuplicateUserException) {
                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.username.exists"));
                        saveErrors(request, errors);
                        return mapping.findForward("ACTION_RETRY");
                    } else {
                        throw e;
                    }
                }
            }
            nodeId = user.getId();
        }
        // Cancel simply displays the original node again
        else {
            nodeId = (Long)session.getAttribute("nodeId");
        }
        request.setAttribute("nodeId", nodeId);
        return mapping.findForward("ACTION_SUCCESS");
    }
    
    public ActionForward changePassword(ActionMapping mapping, 
                                        ActionForm form,
                                        HttpServletRequest request,
                                        HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        Long nodeId = (Long)session.getAttribute("nodeId");
        ChangePasswordActionForm changePasswordAF = (ChangePasswordActionForm)form;
        if (request.getParameter("btnSubmit").equals("OK")) {
            String oldPassword = changePasswordAF.getOldPassword();
            String newPassword = changePasswordAF.getNewPassword1();
            String repeatPassword = changePasswordAF.getNewPassword2();
            ActionErrors errors = new ActionErrors();
            if (newPassword.equals(repeatPassword)) {
                try {
                    lookupUserBean().changePassword(key, nodeId, oldPassword, newPassword);
                }
                catch (EJBException e) {
                    if (e.getCause() instanceof PermissionDeniedException) {
                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.permission.denied"));
                    } else if (e.getCausedByException() instanceof PasswordIncorrectException) {
                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.old.password.not.match"));
                    }
                }
            }
            else {
                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.both.passwords.equal"));
            }
            if (!errors.isEmpty()) {
                saveErrors(request, errors);
                return mapping.findForward("ACTION_RETRY");
            }
        }
        // Cancel simply displays the original user again
        request.setAttribute("nodeId", nodeId);
        return mapping.findForward("ACTION_SUCCESS");
    }
    
    public ActionForward enable(ActionMapping mapping, 
                                ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        Long nodeId = (Long)session.getAttribute("nodeId");
        User user = (User)session.getAttribute("user");
        if (request.getParameter("btnSubmit").equals("OK")) {
            boolean enabled = !user.isEnabled();
            ActionErrors errors = new ActionErrors();
            try {
                lookupUserBean().setUserEnabled(key, nodeId, enabled);
            }
            catch(EJBException e) {
                if (e.getCause() instanceof PermissionDeniedException) {
                    errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.permission.denied"));
                }
            }
            if (!errors.isEmpty()) {
                saveErrors(request, errors);
                return mapping.findForward("ACTION_FAILED");
            }
        }
        // Cancel simply displays the original user again
        request.setAttribute("nodeId", nodeId);
        return mapping.findForward("ACTION_SUCCESS");
    }
    
    public ActionForward showLogins(ActionMapping mapping, 
                                    ActionForm form,
                                    HttpServletRequest request,
                                    HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        User user = lookupUserBean().findUser(key, nodeId);
        ShowNodeAction.setupTreeDisplay(session, user, "Logins");
        session.setAttribute("user", user);
        session.setAttribute("logins", user.getLogins());
        return mapping.findForward("ACTION_DISPLAY");
    }
    
    public ActionForward addBookmarkNode(ActionMapping mapping, 
                                    ActionForm form,
                                    HttpServletRequest request,
                                    HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        lookupUserBean().addBookmarkNode(key, nodeId);
        return mapping.findForward("ACTION_SUCCESS");                                        
    }
    
    public ActionForward removeBookmarkNode(ActionMapping mapping, 
                                            ActionForm form,
                                            HttpServletRequest request,
                                            HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        lookupUserBean().removeBookmarkNode(key, nodeId);
        return mapping.findForward("ACTION_SUCCESS");                                        
    }

    private UserLocal lookupUserBean() {
        try {
            Context c = new InitialContext();
            return (UserLocal) c.lookup("java:comp/env/UserBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private NodeLocal lookupNodeBean() {
        try {
            Context c = new InitialContext();
            return (NodeLocal) c.lookup("java:comp/env/NodeBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
    
}
